<template>
	<view class="menu-container">
		<!-- 头部轮播图 -->
		<view class="banner-section">
			<swiper class="banner-swiper" 
				:indicator-dots="true" 
				:autoplay="true" 
				:interval="3000" 
				:duration="500"
				indicator-color="rgba(255, 255, 255, 0.5)"
				indicator-active-color="#d32f2f">
				<swiper-item v-for="(banner, index) in bannerList" :key="index">
					<image :src="banner.image" class="banner-image" mode="aspectFill"></image>
					<view class="banner-overlay">
						<text class="banner-title">{{ banner.title }}</text>
						<text class="banner-subtitle">{{ banner.subtitle }}</text>
					</view>
				</swiper-item>
			</swiper>
		</view>
		
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 左侧分类列表 -->
			<view class="category-sidebar">
				<view 
					v-for="(category, index) in categories" 
					:key="index"
					class="category-item"
					:class="{ 'active': selectedCategory === index }"
					@click="selectCategory(index)"
				>
					<view class="category-icon">
						<text class="icon">{{ category.icon }}</text>
					</view>
					<text class="category-name">{{ category.name }}</text>
				</view>
			</view>
			
			<!-- 右侧内容区域 -->
			<view class="content-area">
				<view class="empty-state" v-if="!currentCategory.products || currentCategory.products.length === 0">
					<view class="empty-icon">
						<text class="icon">🛍️</text>
					</view>
					<text class="empty-text">该分类暂无商品</text>
					<text class="empty-subtext">可以去看看其他替代商品</text>
				</view>
				
				<view class="product-list" v-else>
					<view 
						v-for="(product, index) in currentCategory.products" 
						:key="index"
						class="product-item"
					>
						<image :src="product.image" class="product-image" mode="aspectFill"></image>
						<view class="product-info">
							<text class="product-name">{{ product.name }}</text>
							<text class="product-price">¥{{ product.price }}</text>
						</view>
						<view class="quantity-control">
							<view class="quantity-btn minus-btn" @click="removeFromCart(product)" v-if="getProductQuantity(product) > 0" :class="{ 'slide-in': getProductQuantity(product) > 0 }">
								<u-icon name="minus-circle-fill" size="32"></u-icon>							</view>
							<text class="quantity-text" v-if="getProductQuantity(product) > 0" :class="{ 'slide-in': getProductQuantity(product) > 0 }">{{ getProductQuantity(product) }}</text>
							<view class="quantity-btn" @click="addToCart(product)">
								<u-icon name="plus-circle-fill" color="#aa0000" size="32"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item" @click="navigateTo('/pages/index/index')">
				<text class="icon">🏠</text>
				<text class="nav-text">首页</text>
			</view>
			<view class="nav-item active" @click="navigateTo('/pages/menu/menu')">
				<text class="icon">🍸</text>
				<text class="nav-text">点单</text>
			</view>
			<view class="nav-item" @click="navigateTo('/pages/profile/profile')">
				<text class="icon">👤</text>
				<text class="nav-text">我的</text>
			</view>
		</view>

		<!-- 悬浮购物车按钮 -->
		<view
			class="floating-cart"
			@click="openCart"
			@touchstart="touchStart"
			@touchmove="touchMove"
			@touchend="touchEnd"
			:style="{ left: cartPosition.x + 'px', top: cartPosition.y + 'px' }"
		>
			<image src="/static/cart.png" alt="" style="width: 45rpx;height: 45rpx;">
			<view class="cart-badge" v-if="cartItemCount > 0">{{ cartItemCount }}</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				selectedCategory: 0,
				cartItemCount: 0,
				bannerList: [
					{
						image: '/static/joyman_banner.jpg',
						title: '一窟一净土·一杯一菩提',
						subtitle: '品味人生，享受当下'
					},
					{
						image: '/static/beer1.png',
						title: '精酿啤酒',
						subtitle: '醇香浓郁，回味无穷'
					},
					{
						image: '/static/Whisky.png',
						title: '威士忌',
						subtitle: '品质之选，经典传承'
					}
				],
				categories: [
					{
						name: '啤酒',
						icon: '🍺',
						products: [
							{
								name: '青岛啤酒',
								price: '8.00',
								image: '/static/beer1.png'
							},
							{
								name: '百威啤酒',
								price: '12.00',
								image: '/static/beer1.png'
							}
						]
					},
					{
						name: '洋酒',
						icon: '🍷',
						products: [
							{
								name: '威士忌',
								price: '88.00',
								image: '/static/Whisky.png'
							}
						]
					},
					{
						name: '小吃',
						icon: '🍰',
						products: []
					},
					{
						name: '果盘',
						icon: '🍎',
						products: []
					},
					{
						name: '手办',
						icon: '🧸',
						products: []
					},
					{
						name: '特调鸡尾酒',
						icon: '🍸',
						products: []
					},
					{
						name: '饮品',
						icon: '🥤',
						products: []
					}
				],
				cartPosition: { x: 0, y: 0 },
				isDragging: false,
				startX: 0,
				startY: 0,
				offsetX: 0,
				offsetY: 0
			}
		},
		computed: {
			currentCategory() {
				return this.categories[this.selectedCategory];
			}
		},
		onShow() {
			// 加载购物车数量
			this.loadCartCount();
			// 加载购物车位置
			this.loadCartPosition();
		},
		mounted() {
			// 初始化购物车位置
			this.initCartPosition();
		},
		methods: {
			initCartPosition() {
				// 获取窗口信息
				const windowInfo = uni.getWindowInfo();
				const screenWidth = windowInfo.screenWidth;
				const screenHeight = windowInfo.screenHeight;
				
				// 计算按钮和导航栏的实际像素大小
				const buttonSize = 50; // 100rpx转换为px
				const bottomNavHeight = 60; // 120rpx转换为px
				const safeAreaBottom = windowInfo.safeAreaInsets?.bottom || 0;
				const margin = 10; // 20rpx转换为px
				
				// 设置初始位置（右下角）
				this.cartPosition = {
					x: screenWidth - buttonSize - margin,
					y: screenHeight - buttonSize - bottomNavHeight - safeAreaBottom - margin
				};
			},
			selectCategory(index) {
				this.selectedCategory = index;
			},
			addToCart(product) {
				// 获取现有购物车数据
				let cartItems = [];
				try {
					const cartData = uni.getStorageSync('cartItems');
					if (cartData) {
						cartItems = JSON.parse(cartData);
					}
				} catch (e) {
					console.error('获取购物车数据失败:', e);
				}
				
				// 检查商品是否已在购物车中
				const existingItem = cartItems.find(item => item.name === product.name);
				if (existingItem) {
					existingItem.quantity++;
				} else {
					cartItems.push({
						...product,
						quantity: 1
					});
				}

				// 保存购物车数据
				try {
					uni.setStorageSync('cartItems', JSON.stringify(cartItems));
					this.cartItemCount = cartItems.reduce((total, item) => total + item.quantity, 0);
					// uni.showToast({
					// 	title: '已添加到购物车',
					// 	icon: 'success'
					// });
				} catch (e) {
					console.error('保存购物车数据失败:', e);
					uni.showToast({
						title: '添加失败',
						icon: 'error'
					});
				}
			},
			loadCartCount() {
				try {
					const cartData = uni.getStorageSync('cartItems');
					if (cartData) {
						const cartItems = JSON.parse(cartData);
						this.cartItemCount = cartItems.reduce((total, item) => total + item.quantity, 0);
					}
				} catch (e) {
					console.error('加载购物车数量失败:', e);
				}
			},
			openCart() {
				// 如果正在拖拽，不触发点击事件
				if (this.isDragging || Math.abs(this.offsetX) > 5 || Math.abs(this.offsetY) > 5) {
					return;
				}
				
				uni.navigateTo({
					url: '/pages/cart/cart'
				});
			},
			navigateTo(url) {
				uni.reLaunch({
					url: url
				});
			},
			touchStart(e) {
				this.isDragging = true;
				this.startX = e.touches[0].clientX;
				this.startY = e.touches[0].clientY;
				this.offsetX = 0;
				this.offsetY = 0;
			},
			touchMove(e) {
				if (!this.isDragging) return;
				
				const currentX = e.touches[0].clientX;
				const currentY = e.touches[0].clientY;
				const deltaX = currentX - this.startX;
				const deltaY = currentY - this.startY;
				
				// 获取窗口信息
				const windowInfo = uni.getWindowInfo();
				const screenWidth = windowInfo.screenWidth;
				const screenHeight = windowInfo.screenHeight;
				
				// 计算新位置
				let newX = this.cartPosition.x + deltaX;
				let newY = this.cartPosition.y + deltaY;
				
				// 边界检测 - 考虑按钮和徽章的实际大小
				const buttonSize = 50; // 100rpx转换为px
				const badgeSize = 20; // 徽章大小
				const bottomNavHeight = 60; // 120rpx转换为px
				const safeAreaBottom = windowInfo.safeAreaInsets?.bottom || 0;
				
				// 限制在屏幕范围内，确保按钮和徽章完全可见
				newX = Math.max(0, Math.min(screenWidth - buttonSize - badgeSize, newX));
				newY = Math.max(0, Math.min(screenHeight - buttonSize - bottomNavHeight - safeAreaBottom, newY));
				
				// 调试信息（可选）
				// console.log('边界信息:', {
				//   screenWidth, screenHeight, buttonSize, badgeSize, 
				//   bottomNavHeight, safeAreaBottom, newX, newY
				// });
				
				this.cartPosition.x = newX;
				this.cartPosition.y = newY;
				
				this.startX = currentX;
				this.startY = currentY;
			},
			touchEnd() {
				if (this.isDragging) {
					// 保存位置到本地存储
					this.saveCartPosition();
				}
				this.isDragging = false;
				this.offsetX = 0;
				this.offsetY = 0;
			},
			saveCartPosition() {
				try {
					uni.setStorageSync('cartPosition', JSON.stringify(this.cartPosition));
				} catch (e) {
					console.error('保存购物车位置失败:', e);
				}
			},
			loadCartPosition() {
				try {
					const positionData = uni.getStorageSync('cartPosition');
					if (positionData) {
						this.cartPosition = JSON.parse(positionData);
					}
				} catch (e) {
					console.error('加载购物车位置失败:', e);
					// 如果加载失败，使用默认位置
					this.initCartPosition();
				}
			},
			getProductQuantity(product) {
				let cartItems = [];
				try {
					const cartData = uni.getStorageSync('cartItems');
					if (cartData) {
						cartItems = JSON.parse(cartData);
					}
				} catch (e) {
					console.error('获取购物车数据失败:', e);
				}
				const item = cartItems.find(item => item.name === product.name);
				return item ? item.quantity : 0;
			},
			removeFromCart(product) {
				let cartItems = [];
				try {
					const cartData = uni.getStorageSync('cartItems');
					if (cartData) {
						cartItems = JSON.parse(cartData);
					}
				} catch (e) {
					console.error('获取购物车数据失败:', e);
				}
				const item = cartItems.find(item => item.name === product.name);
				if (item) {
					item.quantity--;
					if (item.quantity <= 0) {
						cartItems = cartItems.filter(cartItem => cartItem.name !== product.name);
					}
				}
				try {
					uni.setStorageSync('cartItems', JSON.stringify(cartItems));
					this.cartItemCount = cartItems.reduce((total, item) => total + item.quantity, 0);
					// uni.showToast({
					// 	title: '已从购物车移除',
					// 	icon: 'success'
					// });
				} catch (e) {
					console.error('保存购物车数据失败:', e);
					uni.showToast({
						title: '移除失败',
						icon: 'error'
					});
				}
			}
		}
	}
</script>

<style scoped>
.menu-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

.banner-section {
	height: 300rpx;
	position: relative;
	overflow: hidden;
	margin: 0 0 10rpx 0;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.banner-swiper {
	width: 100%;
	height: 100%;
	border-radius: 16rpx;
	overflow: hidden;
}

.banner-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.banner-overlay {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
	padding: 40rpx 30rpx 30rpx;
	color: #fff;
	border-radius: 0 0 16rpx 16rpx;
}

.banner-title {
	font-size: 32rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 8rpx;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
}

.banner-subtitle {
	font-size: 22rpx;
	opacity: 0.9;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.5);
}

.main-content {
	display: flex;
	flex: 1;
	overflow: hidden;
}

.category-sidebar {
	width: 120rpx;
	background-color: #fff;
	border-right: 1rpx solid #eee;
	overflow-y: auto;
}

.category-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
	transition: all 0.3s;
}

.category-item.active {
	background-color: #fff;
	border-left: 4rpx solid #d32f2f;
}

.category-icon {
	margin-bottom: 10rpx;
}

.category-icon .icon {
	font-size: 40rpx;
	color: #d32f2f;
}

.category-name {
	font-size: 24rpx;
	color: #333;
	text-align: center;
}

.content-area {
	flex: 1;
	background-color: #fff;
	position: relative;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100%;
	padding: 100rpx;
}

.empty-icon {
	margin-bottom: 40rpx;
}

.empty-icon .icon {
	font-size: 120rpx;
	color: #ccc;
}

.empty-text {
	font-size: 32rpx;
	color: #999;
	margin-bottom: 20rpx;
}

.empty-subtext {
	font-size: 28rpx;
	color: #ccc;
}

.product-list {
	padding: 30rpx;
}

.product-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	margin-bottom: 20rpx;
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.product-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
	margin-right: 30rpx;
}

.product-info {
	flex: 1;
}

.product-name {
	font-size: 32rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
}

.product-price {
	font-size: 36rpx;
	color: #d32f2f;
	font-weight: bold;
}

.quantity-control {
	display: flex;
	align-items: center;
	margin-left: 30rpx;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	background-color: #f0f0f0;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0 10rpx;
	position: relative;
}

.quantity-btn .icon {
	font-size: 40rpx;
	font-weight: bold;
	line-height: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100%;
}

.minus-btn {
	
}

.plus-btn:active{
	transform: rotate(-90deg);
  transition: all 0.3s ease-out;
}

.quantity-text {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	opacity: 0;
	transform: translateX(-20rpx);
	transition: all 0.3s ease-out;
}

.minus-btn {
	opacity: 0;
	transform: translateX(-20rpx);
	transition: all 0.3s ease-out;
}

.slide-in {
	opacity: 1;
	transform: translateX(0);
}

.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 120rpx;
	background-color: #fff;
	border-top: 1rpx solid #eee;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx;
}

.nav-item .icon {
	font-size: 48rpx;
	color: #666;
	margin-bottom: 8rpx;
}

.nav-item.active .icon {
	color: #d32f2f;
}

.nav-text {
	font-size: 24rpx;
	color: #666;
}

.nav-item.active .nav-text {
	color: #d32f2f;
}

/* 悬浮购物车按钮 */
.floating-cart {
	position: fixed;
	width: 100rpx;
	height: 100rpx;
	background: #666666;
	border-radius: 50rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	z-index: 100;
	transition: none;
	user-select: none;
}

.cart-icon {
	font-size: 48rpx;
	color: #fff;
}

.cart-badge {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	background: #ff5722;
	color: #fff;
	font-size: 20rpx;
	font-weight: bold;
	min-width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 8rpx;
}
</style>
